//
//  EMPoperViewController.m
//  PictureSelector
//
//  Created by Lyy on 15/8/20.
//  Copyright (c) 2015年 Lyy. All rights reserved.
//

#define kDefaultHeight  (167)

#import "EMPoperViewController.h"
#import "EMPoperCollectionViewCell.h"
#import "EMSSlideUpTransitionAnimator.h"
#import <AFNetworking/UIImageView+AFNetworking.h>

static NSString * kCellIdentifier = @"EMPoperCollectionViewCell";

@interface EMPoperViewController ()<
UICollectionViewDataSource,
UICollectionViewDelegate,
UIViewControllerTransitioningDelegate,
UIGestureRecognizerDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UITapGestureRecognizer *tapGestureRecognizer;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) NSArray *activityItems;
@property (nonatomic, strong) NSString *profileImageUrlString;  //

@end

@implementation EMPoperViewController

- (instancetype)initLoginType:(EMUploadProfileLoginType)loginType
              profileImageUrl:(NSString *)urlString {
    self = [super init];
    if (self) {
        self.modalPresentationStyle = UIModalPresentationCustom;
        self.transitioningDelegate = self;
        self.loginType = loginType;
        self.profileImageUrlString = urlString;
        self.activityItems = [self configItems];
    }
    return self;
}

- (void)loadView {
    [super loadView];
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, kDefaultHeight)];
    self.view.backgroundColor = [UIColor whiteColor];
    [self titleLabel];
    [self collectionView];
}

- (NSArray *)configItems {
    
    
    NSMutableArray *array =
    [[NSMutableArray alloc] initWithObjects:[[EMPoperCollectionViewGradeItem alloc] init],
     [[EMPoperCollectionViewPhoneItem alloc] init], nil];
    
     if (self.loginType != EMUploadProfileLoginOther) {
         
         EMPoperCollectionViewThirdLoginItem *item = [[EMPoperCollectionViewThirdLoginItem alloc] init];
         
         if (self.loginType == EMUploadProfileLoginWeibo) {
             item.title = @"微博头像";
         } else {
             item.title = @"QQ头像";

         }
         
         [array insertObject:item atIndex:1];
     }
    
    return [NSArray arrayWithArray:array];
    
}

- (CGSize)preferredContentSize {
    return CGSizeMake(self.view.frame.size.width, kDefaultHeight);
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // this moment the self.view.window != nil
    [self addCloseGestureOnWindow];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self removeGesture];
}

- (void)addCloseGestureOnWindow {
    self.tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapBehind:)];
    self.tapGestureRecognizer.delegate = self;
    [self.view.window addGestureRecognizer:self.tapGestureRecognizer];
}

- (void)removeGesture {
    [self.view.window removeGestureRecognizer:self.tapGestureRecognizer];
}

#pragma mrak -
#pragma mark -UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.activityItems.count;
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    EMPoperCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellIdentifier forIndexPath:indexPath];
    
    EMPoperCollectionViewItem *item = _activityItems[indexPath.row];
    cell.textLabel.text = item.title;
    if (self.loginType != EMUploadProfileLoginOther && indexPath.row == 1) {
        
        [cell.imageView setImageWithURL:[NSURL URLWithString:self.profileImageUrlString]];
        
    } else {
        cell.imageView.image = [UIImage imageNamed:item.imageNamed];
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [self dismissViewControllerAnimated:NO completion:^{
        
        EMPoperCollectionViewItem *item = _activityItems[indexPath.row];
        UIImage *image = [UIImage imageNamed:item.imageNamed];
        self.dismisss(indexPath,image);

    }];
}

#pragma mark UIGestureRecognizerDelegate -
- (void)handleTapBehind:(UITapGestureRecognizer *)sender
{
    // dimiss and clear tapGestureRecognizer
    [self.view.window removeGestureRecognizer:sender];
    [self dismiss:nil];
    self.tapGestureRecognizer = nil;
}

- (void)dismiss:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)sender {
    CGPoint location = [sender locationInView:nil];
    // if tap outside pincode inputscreen
    BOOL inView = [self.view pointInside:[self.view convertPoint:location fromView:self.view.window] withEvent:nil];
    // if tap outside pincode inputscreen
    if (!inView)
    {
        return YES;
    }
    return NO;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return YES;
}

#pragma mark - Setter & Getter
- (UICollectionViewFlowLayout *)collectionViewFlowLayou {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat screenWidth = [UIScreen mainScreen].applicationFrame.size.width;
    CGFloat leftMargin = 20;
    CGFloat pageCount = self.activityItems.count;
    if (self.activityItems.count == 2) {
        leftMargin = 40;
    } else if (self.activityItems.count > 3) {
        pageCount = 3;
    }
    
    flowLayout.itemSize = CGSizeMake((screenWidth-leftMargin*2)/pageCount, 100);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, leftMargin, 0, leftMargin);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    return flowLayout;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        CGRect collectionViewRect = self.view.bounds;
        collectionViewRect.origin.y = CGRectGetMaxY(_titleLabel.frame)+15;
        collectionViewRect.size.height = collectionViewRect.size.height - CGRectGetMinY(collectionViewRect);
        UICollectionViewFlowLayout *flowLayout = [self collectionViewFlowLayou];
        self.collectionView = [[UICollectionView alloc] initWithFrame:collectionViewRect collectionViewLayout:flowLayout];
        self.collectionView.backgroundColor = [UIColor whiteColor];
        self.collectionView.showsHorizontalScrollIndicator = NO;
        [self.collectionView registerNib:[UINib nibWithNibName:@"EMPoperCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kCellIdentifier];
        self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
        [self.view addSubview:self.collectionView];
    }
    return _collectionView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 100, 20)];
        _titleLabel.text = @"设置靓照";
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_titleLabel];
    }
    return _titleLabel;
}

#pragma mark - UIVieControllerTransitioningDelegate -
- (id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented
                                                                   presentingController:(UIViewController *)presenting
                                                                       sourceController:(UIViewController *)source{
    EMSSlideUpTransitionAnimator *slideUpTransitionAnimator = [EMSSlideUpTransitionAnimator animator];
    slideUpTransitionAnimator.presenting = YES;
    return slideUpTransitionAnimator;
}

#pragma mark - Rotate
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    EMSSlideUpTransitionAnimator *slideUpTransitionAnimator = [EMSSlideUpTransitionAnimator animator];
    slideUpTransitionAnimator.presenting = NO;
    return slideUpTransitionAnimator;
}

- (BOOL)shouldAutorotate {
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationPortrait;//|;
}

- (void)dealloc {
    NSLog(@"-----------------------");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
